import './index.scss'
import {
  Button,
  CommonEventFunction,
  Switch,
  SwitchProps,
  View,
  Text
} from '@tarojs/components'
import {observer} from 'mobx-react'
import {useContext, useEffect, useState} from 'react'
import Taro, {useDidHide, useDidShow, useRouter} from '@tarojs/taro'
import {paramStandardSettingStore} from './model'
import {addressJoin} from '@/utils/common'
import StandardUnitPicker from '@/components/picker/standardUnitPicker'
import {
  closeDevStandRange,
  openDevStandRange,
  uEditDevStandRange,
  uSelectDevMsgAndParamStandRange
} from '@/api/setting'
import {checkParamStandard} from '@/utils/standard'
import {getStorage} from '@/utils/localstoreage'

const Paramstandardsetting = () => {
  let router = useRouter()
  // 页面数据源
  const [pageDataSource, setPageDataSource] = useState<
    Setting.ParamStandardSettingDataSource | undefined
  >(undefined)

  // 数据源中的地址信息，组合过后的
  const [address, setAddress] = useState<string>('')

  /**接收标准范围组件返回的范围数据 */
  const [standard, setStandard] = useState('')

  // 是否开启切换时
  const handleIsOpenSwitchOnChange: CommonEventFunction<
    SwitchProps.onChangeEventDetail
  > = e => {
    if (!pageDataSource) {
      Taro.showToast({
        title: '数据源错误',
        icon: 'none'
      })
      return
    }
    if (e.detail.value) {
      openDevStandRange({devSRId: pageDataSource.devStandRange.devSRId})
        .then(res => {
          if (res.msg) {
            Taro.showToast({
              title: res.msg,
              icon: res.result
            })
          }
          updatePageDataSource()
        })
        .catch(err => {
          updatePageDataSource()
        })
    } else {
      closeDevStandRange({devSRId: pageDataSource.devStandRange.devSRId})
        .then(res => {
          if (res.msg) {
            Taro.showToast({
              title: res.msg,
              icon: res.result
            })
          }
          updatePageDataSource()
        })
        .catch(err => {
          updatePageDataSource()
        })
    }
  }

  /**修改数据提交 */
  function handleSubmit() {
    let devSRId = pageDataSource?.devStandRange.devSRId
    if (!devSRId) return
    if (!checkParamStandard(standard)) return
    uEditDevStandRange({devSRId, standRange: standard})
      .then(res => {
        res.msg &&
          Taro.showToast({
            title: res.msg
          })
        updatePageDataSource()
      })
      .catch(err => {
        if (err && err.msg) {
          Taro.showModal({
            title: '提示',
            content: err.msg
          })
        }
      })
  }

  /**更新页面数据源 */
  function updatePageDataSource() {
    let userId = getStorage('userId')
    if (!userId) return
    let devId = router.params['devId']
    let devSRId = router.params['devSRId']
    if (devId && devSRId) {
      uSelectDevMsgAndParamStandRange({devId, devSRId, userId})
        .then(res => {
          // 给数据源赋值
          setPageDataSource(res.data)

          let address =
            addressJoin({
              province: res.data.province,
              district: res.data.district,
              city: res.data.city
            }) || ''
          // 组合地址信息
          setAddress(address)
        })
        .catch(_err => {
          setPageDataSource(undefined)
          setAddress('')
        })
    }
  }

  useEffect(() => {
    updatePageDataSource()
  }, [router])

  // 对应 onShow
  useDidShow(() => {
    console.log('Paramstandardsetting useDidShow')
  })

  // 对应 onHide
  useDidHide(() => {
    console.log('Paramstandardsetting useDidHide')
  })
  return (
    <View className="container bg-xx_bg py-24 px-16">
      {/* 设备名称以及参数单位 */}
      <View className="flex items-center mb-14">
        <View className="text-16 text-black font-medium">
          {pageDataSource?.devName}
        </View>
        <View className="text-14 text-xx_text">
          {pageDataSource?.devStandRange.paramUnit
            ? `(单位：${pageDataSource?.devStandRange.paramUnit})`
            : ''}
        </View>
      </View>

      {/* 地址 */}
      {address ? (
        <View className="hanzi text-14 text-xx_text mb-6">
          {pageDataSource?.devName
            ? address + '-' + pageDataSource?.devName
            : ''}
        </View>
      ) : (
        ''
      )}

      {/* 设备所属人 */}
      {pageDataSource?.devBelong ? (
        <View className="hanzi text-14 text-xx_text mb-24">
          {pageDataSource.devBelong}
        </View>
      ) : (
        ''
      )}

      {/* 参数范围栏 */}
      {pageDataSource?.devStandRange
        ? [
            <View className="hanzi text-14 text-black mb-12">
              {/* 参数名 */}
              {pageDataSource?.devStandRange.paramName}
            </View>,
            <View className="mb-18">
              {/* 标准范围设置 */}
              <StandardUnitPicker
                standard={pageDataSource.devStandRange.standRange}
                paramUnit={pageDataSource.devStandRange.paramUnit}
                onChange={data => {
                  setStandard(data)
                }}
              ></StandardUnitPicker>
            </View>,
            <View className="hanzi text-14 text-black mb-12">标准状态</View>,
            <View className="flex items-center">
              <Switch
                className="statusSwitch"
                checked={pageDataSource.devStandRange.isOpen == 1}
                onChange={handleIsOpenSwitchOnChange}
              ></Switch>
              <View className="hanzi text-14 text-xx_text">
                {pageDataSource.devStandRange.isOpen == 1 ? (
                  '已启用'
                ) : (
                  <Text style="color:#f89898;">已禁用</Text>
                )}
              </View>
            </View>,
            <View className="hanzi text-14 text-xx_text mb-18">
              开启后，监测参数的标准以此为准
            </View>
          ]
        : null}

      <Button
        className="mt-200 rounded-4 bg-primary flex items-center justify-center h-48"
        onClick={handleSubmit}
      >
        <View className="text-16 text-white">保存设置</View>
      </Button>
    </View>
  )
}
export default observer(Paramstandardsetting)
